'use client'

import React, { useState, useEffect } from "react";
import {
  Card,
  CardBody,
  CardHeader,
  Button,
  Textarea,
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
  Divider,
  Spinner,
  Progress,
  Modal,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  RadioGroup,
  Radio,
  useDisclosure
} from "@nextui-org/react";
import { BiCheck, BiMessageSquare } from "react-icons/bi";
import ToastUtil from "@/app/utils/toastUtil";
import axios from "axios";
import cookie from "react-cookies";
import { Token } from "@/app/constants/authTokenConstants";

// 创建axios实例
const apiClient = axios.create({
  baseURL: '/',
  timeout: 60000  // 增加超时时间到60秒
});

// 添加请求拦截器
apiClient.interceptors.request.use(config => {
  const token = cookie.load(Token);
  if (config && config.headers && token) {
    if (token.startsWith('Bearer ')) {
      config.headers['Authorization'] = token;
    } else {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// AI面板属性接口
interface AIPanelProps {
  noteId?: number;    // 笔记ID，编辑模式需要
  noteTitle?: string; // 笔记标题，编辑模式需要
  noteContent?: string; // 笔记内容，编辑模式需要
  onApplyContent?: (content: string) => void; // 应用生成内容的回调
  onApplyTitle?: (title: string) => void;     // 应用生成标题的回调
}

// AI模式定义
interface AIMode {
  key: string;
  name: string;
  description: string;
}

// AI响应接口
interface AIResponseDTO {
  conversationId?: number;
  mode?: string;
  title?: string;
  content?: string;
  suggestedTags?: string[];
  createdAt?: string;
  parsedSummary?: string;
  parsedKeyPoints?: string[];
  structuredData?: string;
}

/**
 * AI笔记助手面板组件 - 简化版
 */
export default function AIPanel({
  noteId,
  noteTitle,
  noteContent,
  onApplyContent,
  onApplyTitle
}: AIPanelProps) {
  // 状态管理
  const [prompt, setPrompt] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [loadingProgress, setLoadingProgress] = useState<number>(0);
  const [loadingMessage, setLoadingMessage] = useState<string>("");
  const [result, setResult] = useState<AIResponseDTO | null>(null);
  const [activeMode, setActiveMode] = useState<AIMode>({
    key: noteId ? "SUMMARIZE" : "CREATE_NOTE",
    name: noteId ? "内容总结" : "创建笔记",
    description: noteId ? "对笔记内容进行总结，提取关键点" : "根据提示词生成完整笔记内容"
  });

  // 内容应用相关状态
  const { isOpen: isApplyModalOpen, onOpen: onOpenApplyModal, onOpenChange: onApplyModalChange } = useDisclosure();
  const [applyMode, setApplyMode] = useState<"replace" | "append">("replace");
  const [contentToApply, setContentToApply] = useState<string>("");

  // 可用的AI模式
  const createModes: AIMode[] = [
    {
      key: "CREATE_NOTE",
      name: "创建笔记",
      description: "根据提示词生成完整笔记内容"
    },
    {
      key: "TECHNICAL_TUTORIAL",
      name: "技术教程",
      description: "生成一个包含章节和代码示例的技术教程"
    },
    {
      key: "CREATIVE_WRITING",
      name: "创意写作",
      description: "生成故事、散文或诗歌等创意内容"
    }
  ];

  const editModes: AIMode[] = [
    {
      key: "SUMMARIZE",
      name: "内容总结",
      description: "对笔记内容进行总结，提取关键点"
    },
    {
      key: "ENHANCE",
      name: "内容增强",
      description: "增强笔记内容，添加更多细节、例子或解释"
    },
    {
      key: "EXTRACT_TAGS",
      name: "提取标签",
      description: "从笔记内容中提取关键词作为标签"
    },
    {
      key: "REWRITE",
      name: "内容改写",
      description: "用不同的表达方式改写笔记内容，保持相同的意思"
    }
  ];

  // 是否为编辑模式（有笔记ID时）
  const isEditMode = !!noteId;

  // 处理模式变更
  const handleModeChange = (mode: AIMode) => {
    setActiveMode(mode);
  };

  // 处理内容生成
  const handleGenerate = async () => {
    if (!prompt.trim()) {
      ToastUtil("请输入提示词", "❌", "error");
      return;
    }

    try {
      setLoading(true);
      setLoadingProgress(0);
      setLoadingMessage("正在准备请求...");

      // 启动进度模拟
      startFakeProgress();

      let response;

      if (isEditMode) {
        // 编辑模式 - 使用内容总结API
        console.log("发送编辑请求:", {
          noteId: noteId,
          mode: activeMode.key,
          prompt: prompt,
          language: "zh",
          includeContent: true,
          content: noteContent,
          title: noteTitle
        });

        setLoadingMessage("正在分析笔记内容...");
        response = await apiClient.post(`/app/ai/edit`, {
          noteId: noteId,
          mode: activeMode.key,
          prompt: prompt,
          language: "zh",
          includeContent: true,
          content: noteContent,
          title: noteTitle
        });
      } else {
        // 创建模式 - 使用创建笔记API
        console.log("发送创建请求:", {
          mode: activeMode.key,
          prompt: prompt,
          language: "zh"
        });

        setLoadingMessage("正在生成笔记内容...");
        response = await apiClient.post(`/app/ai/create`, {
          mode: activeMode.key,
          prompt: prompt,
          language: "zh"
        });
      }

      console.log("AI响应:", response.data);

      if (response.data.code === 200 && response.data.status === true) {
        setLoadingProgress(100);
        setLoadingMessage("内容生成完成！");
        
        // 处理响应数据
        const responseData = response.data.data;
        
        // 解析SUMMARIZE模式下的structuredData
        if (activeMode.key === "SUMMARIZE" && responseData.structuredData) {
          try {
            // 解析structuredData字段的JSON
            const structuredData = JSON.parse(responseData.structuredData);
            
            // 提取关键点数组
            const keyPoints = structuredData.keyPoints || [];
            
            // 创建带有解析内容的结果对象
            const resultWithParsed = {
              ...responseData,
              // content已经包含摘要内容，不需要额外处理
              parsedSummary: responseData.content,
              parsedKeyPoints: keyPoints
            };
            
            setResult(resultWithParsed);
          } catch (e) {
            console.error("解析结构化数据失败:", e);
            setResult(responseData);
          }
        } else {
          setResult(responseData);
        }
        
        ToastUtil("内容生成成功", "✅", "success");
      } else {
        console.error("AI操作失败:", response.data);
        ToastUtil(response.data.message || "AI操作失败: " + JSON.stringify(response.data), "❌", "error");
      }
    } catch (error: any) {
      console.error("生成内容异常:", error);
      let errorMessage = "内容生成失败";

      if (error.response) {
        errorMessage += ": " + (error.response.data?.message || JSON.stringify(error.response.data));
        console.error("错误响应:", error.response.data);
      } else if (error.request) {
        errorMessage += ": 网络请求无响应，请检查网络";
        console.error("请求发送但无响应");
      } else {
        errorMessage += ": " + error.message;
      }

      ToastUtil(errorMessage, "❌", "error");
    } finally {
      setLoading(false);
      setLoadingProgress(0);
      setLoadingMessage("");
    }
  };

  // 模拟进度更新，提供更好的用户体验
  const startFakeProgress = () => {
    let progress = 0;
    const interval = setInterval(() => {
      // 缓慢增加到90%，剩余10%留给实际完成
      progress += 5 * Math.random();
      if (progress > 90) {
        clearInterval(interval);
        progress = 90;
      }
      setLoadingProgress(progress);

      // 根据进度更新不同消息
      if (progress < 30) {
        setLoadingMessage("正在处理您的请求...");
      } else if (progress < 60) {
        setLoadingMessage("AI正在思考...");
      } else if (progress < 80) {
        setLoadingMessage("即将完成...");
      } else {
        setLoadingMessage("正在整理结果...");
      }
    }, 800);

    // 50秒后清除，避免无限运行
    setTimeout(() => {
      clearInterval(interval);
    }, 50000);
  };

  // 应用生成的内容
  const handleApplyContent = () => {
    if (result?.content && onApplyContent) {
      // 现有笔记内容存在且不为空，则打开选择对话框
      if (noteContent && noteContent.trim() !== "") {
        setContentToApply(result.content);
        onOpenApplyModal();
      } else {
        // 直接应用内容
        onApplyContent(result.content);
        ToastUtil("内容已应用", "✅", "success");
      }
    }
  };

  // 确认应用内容
  const confirmApplyContent = () => {
    if (!contentToApply || !onApplyContent) return;

    let finalContent = contentToApply;

    // 如果是追加模式，则将生成的内容添加到现有内容后面
    if (applyMode === "append" && noteContent) {
      finalContent = noteContent + "\n\n" + contentToApply;
    }

    onApplyContent(finalContent);
    ToastUtil("内容已应用", "✅", "success");
    onApplyModalChange(false);
  };

  // 应用生成的标题
  const handleApplyTitle = () => {
    if (result?.title && onApplyTitle) {
      onApplyTitle(result.title);
      ToastUtil("标题已应用", "✅", "success");
    }
  };

  // 添加一个用于调试的useEffect，来检查解析后的数据
  useEffect(() => {
    if (result && activeMode.key === "SUMMARIZE") {
      console.log("解析后的结果:", result);
      console.log("关键点:", result.parsedKeyPoints);
    }
  }, [result, activeMode]);

  return (
    <Card className="w-full">
      <CardHeader className="flex justify-between items-center">
        <div className="flex items-center">
          <BiMessageSquare className="text-primary mr-2 text-xl" />
          <h3 className="text-lg font-medium">AI笔记助手</h3>
        </div>
      </CardHeader>

      <Divider />

      <CardBody className="gap-4 max-h-[70vh] overflow-y-auto">
        {/* 模式选择器 */}
        <Dropdown>
          <DropdownTrigger>
            <Button
              variant="flat"
              className="mb-4"
            >
              {activeMode.name}
            </Button>
          </DropdownTrigger>
          <DropdownMenu
            aria-label="AI模式"
            onAction={(key) => {
              const modes = isEditMode ? editModes : createModes;
              const mode = modes.find(m => m.key === key);
              if (mode) {
                handleModeChange(mode);
              }
            }}
          >
            {(isEditMode ? editModes : createModes).map((mode) => (
              <DropdownItem
                key={mode.key}
                description={mode.description}
                startContent={
                  activeMode.key === mode.key ? <BiCheck className="text-primary" /> : null
                }
              >
                {mode.name}
              </DropdownItem>
            ))}
          </DropdownMenu>
        </Dropdown>

        {/* 提示词输入 */}
        <Textarea
          label="提示词"
          placeholder={isEditMode
            ? "输入提示词，让AI总结你的笔记内容..."
            : "输入提示词，让AI创建笔记内容..."}
          value={prompt}
          onValueChange={setPrompt}
          minRows={3}
          maxRows={5}
          className="mb-4"
          isDisabled={loading}
        />

        {/* 生成按钮 */}
        <Button
          color="primary"
          startContent={loading ? null : <BiMessageSquare />}
          isLoading={loading}
          onPress={handleGenerate}
          className="w-full"
          isDisabled={!prompt.trim() || loading}
        >
          {loading ? "生成中..." : "生成内容"}
        </Button>

        {/* 加载进度条 */}
        {loading && (
          <div className="mt-4">
            <Progress
              value={loadingProgress}
              color="primary"
              className="my-2"
              showValueLabel={true}
              size="md"
            />
            <p className="text-sm text-center text-gray-500">{loadingMessage}</p>
            <p className="text-xs text-center text-gray-400 mt-1">
              AI生成可能需要10-30秒，请耐心等待
            </p>
          </div>
        )}

        {/* 结果展示 */}
        {result && (
          <div className="mt-4 border p-4 rounded-lg">
            {result.title && (
              <div className="mb-4">
                <div className="flex justify-between items-center mb-2">
                  <h4 className="font-medium">生成的标题</h4>
                  {onApplyTitle && (
                    <Button
                      size="sm"
                      variant="flat"
                      color="primary"
                      onPress={handleApplyTitle}
                    >
                      应用
                    </Button>
                  )}
                </div>
                <p className="p-2 bg-gray-100 dark:bg-gray-800 rounded">{result.title}</p>
              </div>
            )}

            {/* 修改内容展示，判断是否有解析后的关键点 */}
            {(result.content || (result.parsedKeyPoints && result.parsedKeyPoints.length > 0)) && (
              <div>
                <div className="flex justify-between items-center mb-2">
                  <h4 className="font-medium">{activeMode.key === "SUMMARIZE" ? "总结结果" : "生成的内容"}</h4>
                  {onApplyContent && (
                    <Button
                      size="sm"
                      variant="flat"
                      color="primary"
                      onPress={handleApplyContent}
                    >
                      应用
                    </Button>
                  )}
                </div>
                
                {/* SUMMARIZE模式下的格式化展示 */}
                {activeMode.key === "SUMMARIZE" && (
                  <div className="space-y-4">
                    {/* 摘要部分 */}
                    {result.content && (
                      <div>
                        <h5 className="text-sm font-medium mb-1 text-primary">摘要</h5>
                        <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                          <p className="whitespace-pre-wrap">{result.content}</p>
                        </div>
                      </div>
                    )}
                    
                    {/* 关键点部分 - 确保即使parsedKeyPoints存在但数组为空也不显示 */}
                    {result.parsedKeyPoints && result.parsedKeyPoints.length > 0 && (
                      <div>
                        <h5 className="text-sm font-medium mb-1 text-primary">关键点</h5>
                        <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                          <ul className="list-disc pl-5 space-y-1">
                            {result.parsedKeyPoints.map((point, index) => (
                              <li key={index} className="whitespace-pre-wrap">{point}</li>
                            ))}
                          </ul>
                        </div>
                      </div>
                    )}
                  </div>
                )}
                
                {/* 普通内容展示（非特殊模式） */}
                {activeMode.key !== "SUMMARIZE" && 
                 activeMode.key !== "TECHNICAL_TUTORIAL" && 
                 activeMode.key !== "CREATIVE_WRITING" && 
                 activeMode.key !== "ENHANCE" && 
                 activeMode.key !== "REWRITE" && 
                 activeMode.key !== "EXTRACT_TAGS" && 
                 result.content && (
                  <div className="p-2 bg-gray-100 dark:bg-gray-800 rounded overflow-auto max-h-[300px]">
                    <pre className="whitespace-pre-wrap font-sans">{result.content}</pre>
                  </div>
                )}
                
                {/* ENHANCE模式的特殊展示 */}
                {activeMode.key === "ENHANCE" && result.structuredData && (
                  <div className="space-y-4">
                    {/* 增强内容部分 */}
                    {result.content && (
                      <div>
                        <h5 className="text-sm font-medium mb-1 text-primary">增强后的内容</h5>
                        <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                          <p className="whitespace-pre-wrap">{result.content}</p>
                        </div>
                      </div>
                    )}
                    
                    {/* 解析并显示新增部分 */}
                    {(() => {
                      try {
                        const parsedData = JSON.parse(result.structuredData);
                        if (parsedData.addedSections && parsedData.addedSections.length > 0) {
                          return (
                            <div>
                              <h5 className="text-sm font-medium mb-1 text-primary">新增部分</h5>
                              <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                                <ul className="list-disc pl-5 space-y-1">
                                  {parsedData.addedSections.map((section, index) => (
                                    <li key={index} className="whitespace-pre-wrap">{section}</li>
                                  ))}
                                </ul>
                              </div>
                            </div>
                          );
                        }
                        return null;
                      } catch (e) {
                        console.error("解析增强内容失败:", e);
                        return null;
                      }
                    })()}
                  </div>
                )}
                
                {/* REWRITE模式的特殊展示 */}
                {activeMode.key === "REWRITE" && result.structuredData && (
                  <div className="space-y-4">
                    {/* 改写内容部分 */}
                    {result.content && (
                      <div>
                        <h5 className="text-sm font-medium mb-1 text-primary">改写后的内容</h5>
                        <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                          <p className="whitespace-pre-wrap">{result.content}</p>
                        </div>
                      </div>
                    )}
                  </div>
                )}
                
                {/* EXTRACT_TAGS模式的特殊展示 */}
                {activeMode.key === "EXTRACT_TAGS" && result.structuredData && (
                  <div className="space-y-4">
                    {/* 提取的标签部分 */}
                    {result.suggestedTags && result.suggestedTags.length > 0 && (
                      <div>
                        <h5 className="text-sm font-medium mb-1 text-primary">提取的标签</h5>
                        <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                          <div className="flex flex-wrap gap-2">
                            {result.suggestedTags.map((tag, index) => (
                              <span key={index} className="px-2 py-1 bg-primary-100 text-primary rounded-full text-sm">
                                {tag}
                              </span>
                            ))}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                )}
                
                {/* TECHNICAL_TUTORIAL模式的特殊展示 */}
                {activeMode.key === "TECHNICAL_TUTORIAL" && result.structuredData && (
                  <div className="space-y-4">
                    {/* 简介部分 */}
                    {result.content && (
                      <div>
                        <h5 className="text-sm font-medium mb-1 text-primary">简介</h5>
                        <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                          <p className="whitespace-pre-wrap">{result.content}</p>
                        </div>
                      </div>
                    )}
                    
                    {/* 解析并显示章节部分 */}
                    {(() => {
                      try {
                        const parsedData = JSON.parse(result.structuredData);
                        if (parsedData.sections && parsedData.sections.length > 0) {
                          return (
                            <div>
                              <h5 className="text-sm font-medium mb-1 text-primary">章节</h5>
                              <div className="space-y-3">
                                {parsedData.sections.map((section, index) => (
                                  <div key={index} className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                                    <h6 className="font-medium">{section.title}</h6>
                                    <p className="whitespace-pre-wrap mt-1">{section.content}</p>
                                  </div>
                                ))}
                              </div>
                            </div>
                          );
                        }
                        return null;
                      } catch (e) {
                        console.error("解析章节数据失败:", e);
                        return null;
                      }
                    })()}
                    
                    {/* 解析并显示代码示例部分 */}
                    {(() => {
                      try {
                        const parsedData = JSON.parse(result.structuredData);
                        if (parsedData.codeExamples && parsedData.codeExamples.length > 0) {
                          return (
                            <div>
                              <h5 className="text-sm font-medium mb-1 text-primary">代码示例</h5>
                              <div className="space-y-3">
                                {parsedData.codeExamples.map((example, index) => (
                                  <div key={index} className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                                    <div className="flex justify-between">
                                      <h6 className="font-medium">{example.language} - {example.description}</h6>
                                      <Button
                                        size="sm"
                                        variant="flat"
                                        color="primary"
                                        onPress={() => {
                                          navigator.clipboard.writeText(example.code);
                                          ToastUtil("代码已复制到剪贴板", "✅", "success");
                                        }}
                                      >
                                        复制
                                      </Button>
                                    </div>
                                    <pre className="text-sm mt-2 p-2 bg-gray-200 dark:bg-gray-900 rounded overflow-auto">
                                      <code>{example.code}</code>
                                    </pre>
                                  </div>
                                ))}
                              </div>
                            </div>
                          );
                        }
                        return null;
                      } catch (e) {
                        console.error("解析代码示例数据失败:", e);
                        return null;
                      }
                    })()}
                  </div>
                )}
                
                {/* CREATIVE_WRITING模式的特殊展示 */}
                {activeMode.key === "CREATIVE_WRITING" && result.structuredData && (
                  <div className="space-y-4">
                    {/* 内容部分 */}
                    {result.content && (
                      <div>
                        <h5 className="text-sm font-medium mb-1 text-primary">内容</h5>
                        <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                          <p className="whitespace-pre-wrap">{result.content}</p>
                        </div>
                      </div>
                    )}
                    
                    {/* 解析并显示创作信息 */}
                    {(() => {
                      try {
                        const parsedData = JSON.parse(result.structuredData);
                        return (
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            {/* 创作类型 */}
                            {parsedData.genre && (
                              <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                                <h5 className="text-sm font-medium mb-1 text-primary">创作类型</h5>
                                <p>{parsedData.genre}</p>
                              </div>
                            )}
                            
                            {/* 主题 */}
                            {parsedData.theme && (
                              <div className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                                <h5 className="text-sm font-medium mb-1 text-primary">主题</h5>
                                <p>{parsedData.theme}</p>
                              </div>
                            )}
                          </div>
                        );
                      } catch (e) {
                        console.error("解析创作信息失败:", e);
                        return null;
                      }
                    })()}
                    
                    {/* 解析并显示角色 */}
                    {(() => {
                      try {
                        const parsedData = JSON.parse(result.structuredData);
                        if (parsedData.characters && parsedData.characters.length > 0) {
                          return (
                            <div>
                              <h5 className="text-sm font-medium mb-1 text-primary">角色</h5>
                              <div className="space-y-2">
                                {parsedData.characters.map((character, index) => (
                                  <div key={index} className="p-3 bg-gray-100 dark:bg-gray-800 rounded">
                                    <h6 className="font-medium">{character.name}</h6>
                                    <p className="text-sm mt-1">{character.description}</p>
                                  </div>
                                ))}
                              </div>
                            </div>
                          );
                        }
                        return null;
                      } catch (e) {
                        console.error("解析角色数据失败:", e);
                        return null;
                      }
                    })()}
                  </div>
                )}
              </div>
            )}

            {/* 标签显示 */}
            {result.suggestedTags && result.suggestedTags.length > 0 && (
              <div className="mt-4">
                <h4 className="font-medium mb-2">推荐标签</h4>
                <div className="flex flex-wrap gap-2">
                  {result.suggestedTags.map((tag, index) => (
                    <span key={index} className="px-2 py-1 bg-primary-100 text-primary rounded-full text-sm">
                      {tag}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* 应用内容确认对话框 */}
        <Modal
          isOpen={isApplyModalOpen}
          onOpenChange={onApplyModalChange}
          backdrop="blur"
        >
          <ModalContent>
            {(onClose) => (
              <>
                <ModalHeader className="flex flex-col gap-1">应用生成内容</ModalHeader>
                <ModalBody>
                  <p>笔记中已有内容，请选择如何应用AI生成的内容：</p>
                  <RadioGroup
                    value={applyMode}
                    onValueChange={(value) => setApplyMode(value as "replace" | "append")}
                  >
                    <Radio value="replace">覆盖 - 替换当前笔记内容</Radio>
                    <Radio value="append">追加 - 将内容添加到当前笔记末尾</Radio>
                  </RadioGroup>
                </ModalBody>
                <ModalFooter>
                  <Button variant="flat" onPress={onClose}>
                    取消
                  </Button>
                  <Button color="primary" onPress={confirmApplyContent}>
                    确认
                  </Button>
                </ModalFooter>
              </>
            )}
          </ModalContent>
        </Modal>
      </CardBody>
    </Card>
  );
} 